package org.openurp.edu.student.info.web.helper

import org.beangle.data.transfer.TransferResult
import org.openurp.edu.student.info.model.Student
import org.openurp.edu.student.info.model.Userstate
import org.openurp.edu.student.info.model.User
import org.beangle.commons.lang.Strings
import org.beangle.data.dao.OqlBuilder
import org.beangle.data.dao.EntityDao
import org.beangle.data.transfer.importer.listener.ItemImporterListener

class ImportStudentListener(entityDao: EntityDao) extends ItemImporterListener {
  override def onItemStart(tr: TransferResult) {
    importer.curData.get("code") foreach { c =>
      entityDao.findBy(classOf[Student], "code", List(c)) foreach { std => this.importer.current = std }
    }
  }

  override def onItemFinish(tr: TransferResult) {
    val std = tr.transfer.current.asInstanceOf[Student]
    entityDao.saveOrUpdate(std)
    if (Strings.isNotEmpty(std.code)) {
      val builder = OqlBuilder.from(classOf[User], "user").where("user.code=:code", std.code)
      val users = entityDao.search(builder)
      if (users.isEmpty) {
        val user = new User()
        user.code = std.code
        user.username = std.name
        user.password = std.code
        val state = new Userstate
        state.id = 3
        user.userstate = state
        entityDao.saveOrUpdate(user)
      }
    }
  }
}